/**
 * Copyright (C), 2021-2024, 广州知铲科技有限公司
 * @ProjectName: android
 * @Package: com.zhichan.mslocator.helper
 * @ClassName: LocatorHelper
 * @Description:
 * @Author: frankylee
 * @CreateDate: 2024/5/11 15:57
 * @UpdateUser: frankylee
 * @UpdateData: 2024/5/11 15:57
 * @UpdateRemark: 更新说明
 */
package com.zhichan.mslocator.helper

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context.LOCATION_SERVICE
import android.location.LocationManager
import android.util.Log
import io.flutter.plugin.common.MethodChannel.Result


class LocatorHelper {

    private var locationManager: LocationManager? = null

    private var activity: Activity? = null

    fun setActivity(activity: Activity?) {
        this.activity = activity
        if (activity != null) {
            val locationService = this.activity?.getSystemService(LOCATION_SERVICE)
            if (locationService != null) {
                locationManager = locationService as LocationManager
            }
        }
    }

    /**
     * 检查是否开启定位服务
     */
    fun checkLocationService(result: Result) {
        val isGps = locationManager?.isProviderEnabled(LocationManager.GPS_PROVIDER)
        val isNetwork = locationManager?.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
        Log.i("checkLocationService", "${isGps}, $isNetwork")
        if (isGps != null && isNetwork != null) {
            result.success(isGps || isNetwork)
        } else {
            result.error("-1", "定位服务出错", null)
        }
    }

    /**
     * 获取最后一次已知位置
     */
    @SuppressLint("MissingPermission")
    fun getLastKnownPosition(result: Result) {
        try {
            val lastNetworkLocation =
                locationManager?.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
            result.success("${lastNetworkLocation?.longitude},${lastNetworkLocation?.latitude}")
        } catch (e: Exception) {
            Log.i("getLastKnownPosition", "getLastKnownPosition: $e")
            result.error("-1", "位置获取出错", null)
        }

    }
}